package j2metris;

import j2metris.game.Game;
import java.util.Vector;
import java.util.Random;
import j2metris.pieces.PieceManager;

public class PieceGenerator
{
    protected final Vector pieceQueue = new Vector();

    protected void fillQueue()
    {
        final PieceManager pieceList = Game.getInstance().getPieceList();
        final Vector tmpPieces = new Vector(7);
        tmpPieces.addElement(pieceList.getI());
        tmpPieces.addElement(pieceList.getJ());
        tmpPieces.addElement(pieceList.getO());
        tmpPieces.addElement(pieceList.getS());
        tmpPieces.addElement(pieceList.getT());
        tmpPieces.addElement(pieceList.getZ());

        final Random rand = new Random(); //comes automatically seeded
        Object nextPiece;
        while(!tmpPieces.isEmpty())
        {
            nextPiece = tmpPieces.elementAt(rand.nextInt(tmpPieces.size()));
            pieceQueue.insertElementAt(nextPiece, 0);
            tmpPieces.removeElement(nextPiece);
        }
        if(J2metrisApp.DEBUG) System.err.println("QUEUE FILLED");
    }

    protected void fillQueueIfNecessary(int positionFromFrontDesiredToBeAccessed)
    {
        while(pieceQueue.size() - 1 < positionFromFrontDesiredToBeAccessed)
        {
            fillQueue();
        }
    }

    public ControllablePiece popNextPiece()
    {
        fillQueueIfNecessary(0);
        final ControllablePiece ret = (ControllablePiece) pieceQueue.elementAt(pieceQueue.size() - 1);
        pieceQueue.removeElement(ret);
//        if(J2metrisApp.DEBUG) System.err.println("POPPED " + ret);
        return ret;
    }

    public ControllablePiece seePieceAt(int position)
    {
        fillQueueIfNecessary(position);
        return ((ControllablePiece) pieceQueue.elementAt((pieceQueue.size() - 1) - position)).clone();
    }
}
